package com.tonghl.juc.queue_study.code;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 资源类
 *
 * 多线程环境先判断不能使用if要使用while
 */
class  ShareData{
    private int number=0;
    private Lock lock=new ReentrantLock();
    private Condition condition=lock.newCondition();

    public void increment() throws  Exception{
        lock.lock();
        try {
            //1.判断
            while (number!=0){
                //等待，不能生产
                condition.await();
            }
            number++;
            System.out.println(Thread.currentThread().getName()+"\t "+number);
            //3通知唤醒
            condition.signalAll();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }


    public void decrement() throws  Exception{
        lock.lock();
        try {
            //1.判断
            while (number==0){
                //等待，不能生产
                condition.await();
            }
            number--;
            System.out.println(Thread.currentThread().getName()+"\t "+number);
            //3通知唤醒
            condition.signalAll();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

}
/**
 * Created by tonghl
 * 传统版阻塞队列
 * 题目：一个初始值为零，两个线程对其交替操作，一个加一，一个减一,来个5轮
 *
 * 1     线程         操作（方法）        资源类
 * 2     判断         干活                通知
 * 3     防止虚假唤醒
 */
public class prodConsumer_TraditionDemo {

    public static void main(String[] args) {
        ShareData shareData = new ShareData();

                      new Thread(()->
                      {
                          for (int i = 1; i <=5 ; i++) {
                              try {
                                  shareData.increment();
                              } catch (Exception e) {
                                  e.printStackTrace();
                              }
                          }
                      },"AA").start();

        new Thread(()->
        {
            for (int i = 1; i <=5 ; i++) {
                try {
                    shareData.decrement();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        },"BB").start();

        new Thread(()->
        {
            for (int i = 1; i <=5 ; i++) {
                try {
                    shareData.increment();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        },"CC").start();

        new Thread(()->
        {
            for (int i = 1; i <=5 ; i++) {
                try {
                    shareData.decrement();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        },"DD").start();

    }

}
